package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"
	"video-guard/models/cache"
	"video-guard/models/mysql"

	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoTopicUserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoTopicUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoTopicUserListLogic {
	return &VideoTopicUserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VideoTopicUserListLogic) VideoTopicUserList(in *videorpc.VideoTopicUserListRequest) (*videorpc.VideoTopicUserListResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("videoTopicUser%s", in)

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	var videoTopicUser []*videorpc.VideoTopicUserList

	var err error

	if result == "" {
		videoTopicUser, err = mysql.VideoTopicUserList(mysql.DB, in.TopicId, in.UploadUserId, in.Page, in.PageSize)

		if err != nil {
			return nil, errors.New("列表失败")
		}

		marshal, _ := json.Marshal(videoTopicUser)

		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*10)

	} else {
		json.Unmarshal([]byte(result), &videoTopicUser)
	}

	return &videorpc.VideoTopicUserListResponse{
		List: videoTopicUser,
	}, nil
}
